function getKey(key) {
  return `_WINTER_${key}_`
}

function get(key) {
  const _key = getKey(key)
  // eslint-disable-next-line
  const result = localStorage.getItem(_key)
  if (result) {
    const {
      data,
      keyInfo: { isOnce, expires, timestamp },
    } = JSON.parse(result) || {}
    if (isOnce) {
      // eslint-disable-next-line
      localStorage.removeItem(_key)
      return data
    }
    if (expires !== -1 && timestamp + expires * 24 * 3600 * 1000 - Date.now() < 0) {
      // 缓存过期
      // eslint-disable-next-line
      localStorage.removeItem(_key)
      return null
    }
    return data
  } else {
    return null
  }
}
function set(key, data, { expires } = { expires: -1 }) {
  const _key = getKey(key)
  if (data) {
    const _data = {
      data,
      keyInfo: {
        expires,
        timestamp: Date.now(),
        isOnce: false,
      },
    }
    // eslint-disable-next-line
    localStorage.setItem(_key, JSON.stringify(_data))
  }
}

function remove(key) {
  const _key = getKey(key)
  // eslint-disable-next-line
  localStorage.removeItem(_key)
}

function once(key, data) {
  const _key = getKey(key)
  if (data) {
    const _data = {
      data,
      keyInfo: {
        expires: -1,
        timestamp: Date.now(),
        isOnce: true,
      },
    }
    // eslint-disable-next-line
    localStorage.setItem(_key, JSON.stringify(_data))
  }
}
export default {
  get,
  set,
  remove,
  delete: remove,
  once,
}
